#pragma once
#include "util.hpp"
#include <vector>
#include <unordered_map>
#include <string>
#include <mutex>

namespace ns_index
{
    class Index
    {
    private:
        Index() {}
        ~Index() {}
        Index(const Index &index) = delete;
        Index operator=(const Index &index) = delete;
        static Index *instance; // 用来表示单例是否创建,不属于任何对象，属于类(因为来类外要调用这个GetInstance)
        static std::mutex mtx;

    public:
        static Index *GetInstance()
        {
            if (nullptr == instance)
            {
                mtx.lock();
                {
                    instance = new Index();
                }
                mtx.unlock();
            }
            return instance;
        }

        // 1.正排索引结构体
        typedef struct DocInfo
        {
            std::string title; // 标题
            std::string content;
            std::string url;
            u_int64_t doc_id; // 在正排索引的位置
        } DocInfo_t;

        struct InvertedElem
        {
            u_int64_t doc_id; // 对应的正排索引的文档号
            std::string word; // 对应倒排索引的单词
            int weight;       // 权重，用来进行页面排序
        };

        typedef std::vector<InvertedElem> InvertedList_t;

    private:
        std::vector<DocInfo_t> forward_index;                                      // 正排索引结构
        std::unordered_map<std::string, std::vector<InvertedElem>> inverted_index; // 倒排索引结构

    public:
        // 根据doc_id找到找到文档内容
        DocInfo *GetForwardIndex(uint64_t doc_id)
        {
            if (doc_id >= forward_index.size())
            {
                std::cerr << "doc_id out range, error!" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }

        // 根据关键字string，获得倒排拉链
        InvertedList_t *GetInvertedList(const std::string &word)
        {
            auto iter = inverted_index.find(word);
            if (iter == inverted_index.end())
            {
                std::cerr << word << " have no InvertedList" << std::endl;
                return nullptr;
            }
            return &(iter->second);
        }

        bool BuildIndex(const std::string &input) // parse处理完毕的数据交给我
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open())
            {
                std::cerr << "sorry, " << input << " open error" << std::endl;
                return false;
            }

            std::string line;
            int count = 0;
            while (std::getline(in, line))
            {
                DocInfo_t *doc = BuildForwardIndex(line);
                if (nullptr == doc)
                {
                    std::cerr << "build " << line << " error" << std::endl; // for deubg
                    continue;
                }

                BuildInvertedIndex(*doc);
                count++;
                if (count % 50 == 0)
                {
                    std::cout << "当前已经建立的索引文档: " << count << std::endl;
                }
            }
            return true;
        }

        // 创建正排索引，一个下标对应一个DocInfo_t对象
        DocInfo_t *BuildForwardIndex(const std::string &line)
        {
            std::string SEP = "\3";
            std::vector<std::string> results;
            ns_util::SplitString::Split(line, &results, SEP); // 此时results存放了结果
            if (results.size() != 3)
            {
                return nullptr;
            }
            DocInfo_t doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size();
            forward_index.push_back(std::move(doc));

            return &(forward_index.back());
        }

        void BuildInvertedIndex(const DocInfo_t &doc)
        {
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt() : title_cnt(0), content_cnt(0)
                {
                }
            };
            // 创建存放词和对应出现次数的map表
            std::unordered_map<std::string, word_cnt> Word_cnt;
            // doc中存放了标题，内容和url
            // 对标题，正文进行分词，统计标题，正文出现的词和次数
            // 最终去遍历这些出现的词，构建每个词对应的倒排拉链
            std::vector<std::string> title_word;
            ns_util::JiebaUtil::CutString(doc.title, &title_word);
            for (auto word : title_word)
            {
                boost::to_lower(word);
                Word_cnt[word].title_cnt++;
            }

            std::vector<std::string> content_word;
            ns_util::JiebaUtil::CutString(doc.content, &content_word);
            for (auto word : content_word)
            {
                Word_cnt[word].content_cnt++;
            }
#define X 10
#define Y 1
            // 此时Word_cnt存放当前文档的所有出现的词和对应在各个位置出现的次数，此时可以去构建倒排索引中该文档对应的InvertedElem
            for (auto word_pair : Word_cnt)
            {
                InvertedElem item;
                item.weight = (word_pair.second.content_cnt) * Y + (word_pair.second.title_cnt) * X;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                InvertedList_t &invertedlist = inverted_index[word_pair.first];
                invertedlist.push_back(std::move(item));
            }
            return; // 此时就会重复利用每个传进来的doc去进行构造倒排索引
        }
    };
    Index *Index::instance = nullptr; // 用来表示单例是否创建
    std::mutex Index::mtx;
}
